package com.lqk.netty.inboundhandlerandoutboundhandler.client;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class MyClientHandler extends SimpleChannelInboundHandler<Long> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        System.out.println("服务器得我ip="+ctx.channel().remoteAddress());
        System.out.println("收到服务器消息="+msg);
    }

    // 重写 channelActive 发送数据

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler 发送数据");

        /**
         * 分析
         *  1. "abcdabcdabcdabcd" 是16个字节
         *  2. 该处理器的前一个 handler 是 MyLongToByteEncoder
         *  3. MyLongToByteEncoder 父类 MessageToByteEncoder
         *  4. 父类 MessageToByteEncoder
         *      public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
         *         ByteBuf buf = null;
         *
         *         try {
         *             if (this.acceptOutboundMessage(msg)) {   // 判断当前 msg 是不是应该处理的类型，如果是就处理，不是就跳过 encoder
         *                 I cast = msg;
         *                 buf = this.allocateBuffer(ctx, msg, this.preferDirect);
         *
         *                 try {
         *                     this.encode(ctx, cast, buf);
         *                 } finally {
         *                     ReferenceCountUtil.release(msg);
         *                 }
         *
         *                 if (buf.isReadable()) {
         *                     ctx.write(buf, promise);
         *                 } else {
         *                     buf.release();
         *                     ctx.write(Unpooled.EMPTY_BUFFER, promise);
         *                 }
         *
         *                 buf = null;
         *             } else {
         *                 ctx.write(msg, promise);
         *             }
         * 5. 因此我们编写的 Encoder 是要注意传入的数据类型和处理的数据类型要一致
         */
        ctx.writeAndFlush(Unpooled.copiedBuffer("abcdabcdabcdabcd",CharsetUtil.UTF_8));

//        ctx.writeAndFlush(123456L); // 发送Long
    }
}
